%% @author Administrator
%% @doc @todo Add description to fun_scene_lh.


-module(fun_scene_lh).
-include("common.hrl").

-export([init_lh/1,join_game/1,robot_bets/0,bets/1,game_process/0,game_over/0,bet_controller/1,leave_lh/1]).
-export([broad_status/0,movie/0,broad_status_stop/0]).




%% @doc 初始化
init_lh(_ArgList)->
	?debug("init_lh"),
	erlang:put(usr, []),
	init_robot_info(),
	game_process().


%% @doc 特殊处理 播动画时间
movie()->
	broad_cast(?PT_RES_GAME_STATUS, {1,0}),
	timer:apply_after(3000, gen_server, cast, [self(), {game_process}]).


%% @doc 游戏流程
game_process()->ok.
%% 	start_game(),
%% 	erlang:put(?GAME_STATUS, start),
%% 	erlang:put(?DEASL_TIME, 10),
%% 	broad_status(),
%% 	bet_controller(3),
%% 	timer:apply_after(10000, gen_server, cast, [self(), {game_over}]).

%% @doc 开始游戏
start_game()->
	NewBets=dict:new(),
	erlang:put(bets, NewBets),
	erlang:put(dragon_poker,no),
	erlang:put(tiger_poker, no),
	init_card(0,[]),
	fresh_and_deal_poker(),
   	ok.


	
%% @doc 结算
game_over()->
	erlang:put(?GAME_STATUS, stop),
	erlang:put(?STOP_TIME, 5),
	UsrList=get_final_player_data(),
	CardList=get_final_card_info(),
	broad_cast(?PT_RES_GAME_OVER_INFO,{CardList,UsrList}),
	broad_cast(?PT_RES_GAME_STATUS, {get_status(),0}),
	timer:apply_after(6500, gen_server, cast, [self(), {broad_status_stop}]).
	


%% @doc 比牌计算
deal_game()->
	cal_bet_final(),
	cal_player_final().

%% @doc 离开房间
leave_lh(Uid)->
	case erlang:get(usr) of
		List when erlang:length(List)>0->
			case lists:member(Uid, List) of
				true->
				Rest=lists:delete(Uid, List),
				erlang:erase(Uid),
				erlang:put(usr, Rest);
				_->skip
			end;
			_->skip
		end.
%% broad_status_usr(Sid)->
%% 	case erlang:get(?GAME_STATUS) of
%% 		start->
%% 		Deal_time=erlang:get(?DEASL_TIME),
%% 		pt:send(Sid,Cmd,Data)
%% 		_->skip
%% 	end.
broad_status_stop()->
	case erlang:get(?GAME_STATUS) of
		stop->
			Stop_time=erlang:get(?STOP_TIME),
			if
				Stop_time>0->
					broad_cast(?PT_RES_GAME_STATUS, {get_status(),Stop_time}),
					erlang:put(?STOP_TIME, Stop_time-1),
					timer:apply_after(1000, gen_server, cast, [self(), {broad_status_stop}]);
				true->
					timer:apply_after(100, gen_server, cast, [self(), {movie}])
			end;
		_->skip
	end.
	
broad_status()->
	case erlang:get(?GAME_STATUS) of
		start->
		Deal_time=erlang:get(?DEASL_TIME),
		broad_cast(?PT_RES_GAME_STATUS, {get_status(),Deal_time}),
		erlang:put(?DEASL_TIME, Deal_time-1),
		timer:apply_after(1000, gen_server, cast, [self(), {broad_status}]);
		_->skip
	end.

init_robot_info()->
	Robots=get_robot_info(100,dict:new()),
	erlang:put(robots, Robots).


get_robot_info(0,Dict)->Dict;	
get_robot_info(Num,Dict)->
	ID=get_robot_id(),
	Head=rand:uniform(50),
	Name="机器人"++util:to_list(ID),
	Coin=1000000,
	Robot=#player{id=ID,ai=yes,head_id=Head,name=Name,coin=Coin,currency=0},
	NewDict=dict:store(ID, Robot, Dict),
	get_robot_info(Num-1,NewDict).

get_robot_id()->
	case erlang:get(machineId) of
		?UNDEFINED->
			erlang:put(machineId, ?MachineId+1),
			?MachineId;
		Num when erlang:is_integer(Num)->
			erlang:put(machineId, Num+1),
			Num
	end.
 
 
join_game({Uid,Sid,Name,HeadId,Coin})->
%% 	?debug("Name=~p,HeadId=~p,Coin=~p",[Name,HeadId,Coin]),
	erlang:put(usr, [Uid]),
	erlang:put(Uid, #player{ai=no,sid=Sid,id=Uid,head_id=HeadId,name=Name,coin=Coin}),
	UsrList=get_player_data(),
	?debug("UsrList=~p",[UsrList]),
	gen_server:cast(Sid,{set_val, scene_pid, self()}),
	pt:send(Sid, ?PT_RES_JOIN_GAME, {UsrList,100,get_status()}).

get_status()->
	fun_scene_usr:get_status().


init_card(0,L)->L;
init_card(Num,L)->
	F=fun(N,List)->
			  List++[{#card{col=Num,value=N},1}] 
	  end,
	Col1=lists:foldl(F, [], ?CardValueList),
	init_card(Num-1,L++Col1).
	  
%% @doc 洗牌 发牌
fresh_and_deal_poker()->
	CardList=init_card(4, []),
	{RandDragonCard,Rest}=util:random_by_weight_ex(CardList),
	{RandTigerCard,_}=util:random_by_weight_ex(Rest),
	?debug("RandDragonCard=~p,RandTigerCard=~p",[RandDragonCard,RandTigerCard]),
	erlang:put(dragon_poker, RandDragonCard),
	erlang:put(tiger_poker, RandTigerCard).



	
get_rand_select(1)->peace;
get_rand_select(2)->peace;
get_rand_select(3)->dragon;
get_rand_select(4)->peace;
get_rand_select(5)->tiger;
get_rand_select(6)->dragon;
get_rand_select(7)->tiger;
get_rand_select(8)->dragon;
get_rand_select(9)->tiger;
get_rand_select(10)->dragon.

get_type(dragon)->1;
get_type(tiger)->2;
get_type(peace)->3.

get_select(1)->dragon;
get_select(2)->tiger;
get_select(3)->peace.

%% @doc 下注
get_rand_bets_info()->
	Bets=util:random_by_weight([{0,5},{100,1},{500,1},{1000,1},{5000,1},{10000,1}]),
	RandBetNum=util:rand(1, 10),
	RandScelect=get_rand_select(RandBetNum),
	Type=get_type(RandScelect),
	{Bets,Type}.
update_select(Scelet,Bets,List)->
	case lists:keyfind(Scelet, 1, List) of
		false->lists:keystore(Scelet, 1, List, {Scelet,Bets});
		{Slect,Old}->
			lists:keyreplace(Scelet, 1, List, {Slect,Old+Bets})
	end.
%% 机器人下注
robot_bets()->
%% 	?debug("~p~w",["机器人下注"]),
	Robots=erlang:get(robots),
	F=fun(_Key,Player,{DictNew,L})->
			  #player{id=ID,coin=Coin,select=OldSelectList}=Player,
			  {Bets,RandScelect}=get_rand_bets_info(),
			  NewSlectList=update_select(RandScelect,Bets,OldSelectList),
			  NewPlayer=
			  if
				  Bets =< Coin ->Player#player{coin=Coin-Bets,select=NewSlectList};
				  true->Player
			  end,
			  NewL=if
					   Bets=/=0->
					   L++[{ID,RandScelect,Bets,NewPlayer#player.coin,0,0}];
					   true->L
				   end,	
%% 			  ?debug("NewL=~p",[NewL]),
			  {dict:store(ID, NewPlayer, DictNew),NewL} end,
	{BetsDict,BetList}=dict:fold(F, {dict:new(),[]}, Robots),
%% 	?debug("BetList=~p",[BetList]),
	erlang:put(robots, BetsDict),
%% 	?debug("BetsDict=~p",[BetsDict]),
	broad_cast(?PT_RES_GAME_BETS, {BetList}).
	

bets({{Bets,Type,X,Y},Uid,_Sid})->
	case get_status() of 
		1->
			case lists:member(Bets, [100,500,1000,5000,10000]) of
				true->
					UsrInfo=#player{coin=Coin,select=OldList}=erlang:get(Uid),
					Scelet=get_select(Type),
					NewList=update_select(Scelet,Bets,OldList),
					NewUsrInfo=
						if
							Bets =< Coin-> UsrInfo#player{coin=Coin-Bets,select=NewList};
							true->UsrInfo
						end,
					erlang:put(Uid, NewUsrInfo),
					broad_cast(?PT_RES_GAME_BETS, {[{Uid,Type,Bets,Coin-Bets,X,Y}]});
				_->skip
			end;
		_->skip
	end.
cal_card_value()->
	#card{value=Value1}=erlang:get(dragon_poker),
	#card{value=Value2}=erlang:get(tiger_poker),
	if
		Value1>Value2->1;
		Value2>Value1->2;
		true->3
	end.
cal_bet_final(3,SceletList)->
	F=fun({Select,Bets},N)->
			if
				Select==3 ->N+Bets*8;
				true->N+Bets
			end end,
	lists:foldl(F, 0, SceletList);
cal_bet_final(1,SceletList)->
		F=fun({Select,Bets},N)->
			if
				Select==1 ->N+Bets;
				true->N
			end end,
	lists:foldl(F, 0, SceletList);
cal_bet_final(2,SceletList)->
	F=fun({Select,Bets},N)->
			if
				Select==2 ->N+Bets;
				true->N
			end end,
	lists:foldl(F, 0, SceletList).
  
  
cal_player_final()->
	UsrList=erlang:get(usr),
	F=fun(Uid)->
		Player=#player{select=Scelet,coin=Coin}=erlang:get(Uid),
		Final=cal_card_value(),
		FinalBets=cal_bet_final(Final,Scelet),
	    CoinFinal=Coin+FinalBets,
	    NewPlayer=Player#player{coin=CoinFinal,select=[]},
		erlang:put(Uid, NewPlayer) end,
	lists:foreach(F, UsrList).
	
cal_bet_final()->
	Robot=erlang:get(robots),
	Final=cal_card_value(),
	F=fun(_Key,Player=#player{select=Scelet,coin=Coin,id=Id},Dict)->
			  FinalBets=cal_bet_final(Final,Scelet),
			  CoinFinal=Coin+FinalBets,
			 NewPlayer=Player#player{coin=CoinFinal,select=[]},
	  		dict:store(Id, NewPlayer, Dict) end,
	 NewRobot=dict:fold(F, dict:new(), Robot),
	 erlang:put(robots,NewRobot).





bet_controller(Num)->
	if
		Num>0->
		robot_bets(),
		timer:apply_after(3000, gen_server, cast, [self(), {bet_controller,Num-1}]);
		true->deal_game()
	end.
get_player_data()->
	Robots=erlang:get(robots),
	UsrFinalInfo=
		case erlang:get(usr) of
			UsrList when length(UsrList)>0->
				F=fun(Uid,L)->
						  #player{coin=Coin,head_id=Head,name=Name}=
							  erlang:get(Uid),	
						  L++[{Uid,Coin,Head,Name}] end,
				lists:foldl(F, [], UsrList);
			_->[]
		end,
	List=get_robot_start_info(Robots,6), 
	?debug("List=~p",[List]),
	List++UsrFinalInfo.

get_robot_start_info(Robots,Num)->
	F=fun(_KEY,#player{id=Uid,coin=Coin,head_id=Head,name=Name},R)-> 
			  R++[{Uid,Coin,Head,Name}] end,
	L=dict:fold(F, [], Robots),
	lists:sublist(L, Num).

get_final_player_data()->
	Robots=erlang:get(robots),
	UsrFinalInfo=
		case erlang:get(usr) of
			UsrList when length(UsrList)>0->
				F=fun(Uid,L)->
						  #player{coin=Coin}=
							  erlang:get(Uid),	
						  L++[{Uid,Coin}] end,
				lists:foldl(F, [], UsrList);
			_->[]
		end,
	List=dict_to_list(Robots,6),
	List++UsrFinalInfo.

dict_to_list(Robots,Num)->
	F=fun(_KEY,#player{id=Uid,coin=Coin},R)-> 
			  R++[{Uid,Coin}] end,
	L=dict:fold(F, [], Robots),
	NL=lists:sublist(L, Num),
	F1=fun({_,Coin1},{_,Coin2})->
			   Coin1>=Coin2 end,
	lists:sort(F1, NL).

				
get_final_card_info()->
	#card{col=Col1,value=Value1}=erlang:get(dragon_poker),
	#card{col=Col2,value=Value2}=erlang:get(tiger_poker),
	[{Col1,Value1},{Col2,Value2}].
	



broad_cast(Cmd,Data)->
	UsrList=erlang:get(usr),
	F=fun(Uid)->
		#player{sid=Sid}=erlang:get(Uid),
		pt:send(Sid,Cmd,Data)
	  	end,
	lists:foreach(F, UsrList).

